package com.appspot.yourvirtualgymtrainer;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.Entity;


@SuppressWarnings("serial")
public class SizeServlet extends BaseServlet {
	
private static final Logger logger = Logger.getLogger(SizeServlet.class.getCanonicalName());
	
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
		 throws ServletException, IOException {
	HttpSession sess = req.getSession(true);
	System.out.println("jest zalogowany " + sess.getAttribute("isLogged"));
	PrintWriter out = resp.getWriter();
	try{
		if(!sess.getAttribute("isLogged").equals("no")) {
			super.doGet(req, resp);
			//logger.log(Level.INFO, "Pobranie rozmiaru");
			String login = (String) sess.getAttribute("isLogged");
			Entity entity = Size.getSize(login);
			if(entity != null){
				System.out.println(Util.writeOneJSON(entity));
				 out.println(Util.writeOneJSON(entity));
			}	
		} else {
			sess.setAttribute("isLogged", "no");
			resp.setContentType("text/plain; charset=utf-8");
			out.println("niezalogowany");
		}
	} catch(NullPointerException e) {
		resp.setContentType("text/plain; charset=utf-8");
		out.println("niezalogowany");
	}
}

/**
 * Creates entity and persists the same
 */
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
	HttpSession sess = req.getSession(true);
  logger.log(Level.INFO, "Tworze rozmiar");
  System.out.println("test get");
  Map<String, String[]> parameters = req.getParameterMap();
//  String name = req.getParameter("name");
//  String surname = req.getParameter("surname");
  String login = (String) sess.getAttribute("isLogged");
  Size.updateSize(login, parameters);
}

/**
 * Redirects to delete or insert entity based on the action in the HTTP
 * request.
 */
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
	System.out.println("test POst");
  String action = req.getParameter("action");
  if (action.equalsIgnoreCase("delete")) {
    doDelete(req, resp);
    return;
  } else if (action.equalsIgnoreCase("put")) {
    doPut(req, resp);
    return;
  }
}


}
